package io.itit.ecp.admin.server.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import icu.mhb.mybatisplus.plugln.base.service.impl.JoinServiceImpl;
import io.itit.ecp.admin.server.entity.EnergyDataEntity;
import io.itit.ecp.admin.server.entity.SceneCompanyEntity;
import io.itit.ecp.admin.server.entity.SceneRoomEntity;
import io.itit.ecp.admin.server.mapper.SceneCompanyMapper;
import io.itit.ecp.admin.server.service.IEnergyDataService;
import io.itit.ecp.admin.server.service.ISceneCompanyService;
import io.itit.ecp.admin.server.service.ISceneRoomService;
import io.itit.grass.common.exception.GrassException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 *
 * @Author：Roy
 * @Description：公司服务实现类
 * @Date：Create by 2023-11-23 09:55:21
 */
@Service
public class SceneCompanyServiceImpl extends JoinServiceImpl<SceneCompanyMapper, SceneCompanyEntity> implements ISceneCompanyService {

    @Resource
    private ISceneRoomService sceneRoomService;
    @Resource
    private IEnergyDataService energyDataService;

    @Override
    public boolean saveCompany(SceneCompanyEntity companyEntity, List<String> roomIds) {
        return this.save(companyEntity) && sceneRoomService.updateCompanyId(companyEntity.getId(), roomIds);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean removeCompany(List<String> ids) {

        // 查询关联的空间.
        long countRo = sceneRoomService.lambdaQuery()
                .select(SceneRoomEntity::getId)
                .in(SceneRoomEntity::getSceneCompanyId, ids)
                .count();
        GrassException.throwEx(countRo > 0, "项目已被空间模块关联，请在解绑后重试！");

        // 查询关联的能源数据
        long countEnergyData = energyDataService.lambdaQuery()
                .select(EnergyDataEntity::getId)
                .in(EnergyDataEntity::getSceneCompanyId, ids)
                .count();
        GrassException.throwEx(countEnergyData > 0, "项目已被能源数据模块关联，请在解绑后重试！");

        return this.removeBatchByIds(ids, 1000);
    }


    @Override
    public boolean updateCompany(SceneCompanyEntity companyEntity, List<String> roomIds, List<String> cancelRoomIds) {
        boolean res = this.updateById(companyEntity);
        // 删除公司的关联空间
        if (CollectionUtil.isNotEmpty(cancelRoomIds)) {
            // 取消关联的房间
            res = res && sceneRoomService.lambdaUpdate()
                    .set(SceneRoomEntity::getSceneCompanyId, null)
                    .in(SceneRoomEntity::getId, cancelRoomIds)
                    .update();
        }


        // 新增公司的关联空间
        return res && sceneRoomService.updateCompanyId(companyEntity.getId(), roomIds);
    }
}
